package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 西门凌兰
 * @version 1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //1.处理各种业务异常，(地址为空，购物车为空)
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //获取用户id
        Long userId = BaseContext.getCurrentId();

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2.向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);


        orderMapper.insert(orders);
        //3.向订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //4.清空当前用户的购物车数据
        shoppingCartMapper.clean(userId);
        //5.封装Vo返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

        return orderSubmitVO;

    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
//    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//
//
//
//        return vo;
//    }

    /**
     * 模拟订单支付
     *
     * @param ordersPaymentDTO
     * @return
     * @throws Exception
     */
    public void payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        Orders orders = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setCheckoutTime(LocalDateTime.now());
        //支付成功，修改订单状态
        orderMapper.update(orders);

        //通过websocket向客户端浏览器推送消息  type orderId content
        Map map = new HashMap();
        map.put("type", 1);//1表示来单提醒，2表示客户催单
        map.put("orderId", orders.getId());
        map.put("content", "订单号:" + orders.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

//         根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);


    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult list(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.list(ordersPageQueryDTO);
        long total = page.getTotal();
        //有些订单需要返回菜品信息，将Orders转为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page.getResult());

        return new PageResult(total, orderVOList);
    }

    /**
     * @param orders
     * @return
     */
    public List<OrderVO> getOrderVOList(List<Orders> orders) {
        List<OrderVO> orderVOList = new ArrayList<>();
        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                //将order中相同的数据拷贝到orderVO中
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                String orderDishes = getOrderDishes(order.getId());
                orderVO.setOrderDishes(orderDishes);
                String address = getAddress(order.getAddressBookId());
                orderVO.setAddress(address);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id查询对应的菜品信息，并返回字符串的形式
     *
     * @param orderId
     * @return
     */
    public String getOrderDishes(Long orderId) {
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
        String orderDishes = "";
        if (orderDetails != null && orderDetails.size() > 0) {
            for (OrderDetail orderDetail : orderDetails) {
                orderDishes = orderDishes + orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            }
        }
        return orderDishes;
    }

    /**
     * 根据地址薄id查询地址薄信息，并返回字符串的形式
     *
     * @param addressId
     * @return
     */
    public String getAddress(Long addressId) {
        AddressBook addressBook = addressBookMapper.getById(addressId);
        return addressBook.getProvinceName() + addressBook.getCityName() +
                addressBook.getDistrictName() + addressBook.getDetail();
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(@RequestBody OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        /*
        - 商家拒单其实就是将订单状态修改为“已取消”
        - 只有订单处于“待接单”状态时可以执行拒单操作
        - 商家拒单时需要指定拒单原因
        - 商家拒单时，如果用户已经完成了支付，需要为用户退款
         */
        Orders order = orderMapper.getById(ordersRejectionDTO.getId());
        if (order == null || order.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //判断是否支付，如果支付，则退款
        if (order.getPayStatus() == Orders.PAID) {
            //已支付，退款
            String refund = weChatPayUtil.refund(
                    order.getNumber(),
                    order.getNumber(),
                    order.getAmount(),
                    order.getAmount()
            );
            log.info("退款：{}", refund);
        }
        //修改订单状态，拒单原因，取消时间
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        /*
            取消订单其实就是将订单状态修改为“已取消”
            - 商家取消订单时需要指定取消原因
            - 商家取消订单时，如果用户已经完成了支付，需要为用户退款
         */
        Orders order = orderMapper.getById(ordersCancelDTO.getId());
        //判断用户是否支付，如果支付，则为用户退款
        if (order.getPayStatus() == Orders.CANCELLED) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    order.getNumber(),
                    order.getNumber(),
                    order.getAmount(),
                    order.getAmount()
            );
            log.info("退款:{}", refund);
        }
        //修改订单状态，取消原因，取消时间
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO count() {
        Integer count1 = orderMapper.getCount(Orders.TO_BE_CONFIRMED);
        Integer count2 = orderMapper.getCount(Orders.CONFIRMED);
        Integer count3 = orderMapper.getCount(Orders.DELIVERY_IN_PROGRESS);
        return new OrderStatisticsVO(count1, count2, count3);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        /*
            派送订单其实就是将订单状态修改为“派送中”
            只有状态为“待派送”的订单可以执行派送订单操作
         */
        Orders order = orderMapper.getById(id);
        if (order == null || order.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态为派送中
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(order);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        /*
            - 完成订单其实就是将订单状态修改为“已完成”
            - 只有状态为“派送中”的订单可以执行订单完成操作
         */
        Orders order = orderMapper.getById(id);
        if (order == null || order.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态为已完成
        order.setStatus(Orders.COMPLETED);

        orderMapper.update(order);
    }

    /**
     * 根据订单id查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders order = orderMapper.getById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 用户历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        /*
        - 分页查询历史订单
        - 可以根据订单状态查询
        - 展示订单数据时，需要展示的数据包括：下单时间、订单状态、订单金额、订单明细（商品名称、图片）
         */
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //得到userId
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        //查询该用户的订单
        Page<Orders> page = orderMapper.list(ordersPageQueryDTO);

        //返回的数据需要订单详细信息，需要将Orders对象转为OrderVO对象
        List<Orders> orders = page.getResult();
        List<OrderVO> orderVOList = new ArrayList<>();
        if (page != null && page.getTotal() > 0) {
            for (Orders order : orders) {
                OrderVO orderVO = new OrderVO();
                //将相同的属性拷贝
                BeanUtils.copyProperties(order, orderVO);
                //通过订单id查询对应的订单详细信息
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(order.getId());
                //设置orderVO的订单详细信息
                orderVO.setOrderDetailList(orderDetails);
                //将该orderVO对象存入orderVOList
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrder(Long id) throws Exception {
        /*
        业务规则：
        - 待支付和待接单状态下，用户可直接取消订单
        - 如果在待接单状态下取消订单，需要给用户退款
        - 商家已接单状态下，用户取消订单需电话沟通商家
        - 派送中状态下，用户取消订单需电话沟通商家
        - 取消订单后需要将订单状态修改为“已取消”
         */
        //获取订单信息
        Orders order = orderMapper.getById(id);
        //判断订单是否存在
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //判断订单状态 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (order.getStatus() > 2) {
            //该订单已接单或在派送中
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(id);
        //判断该订单是否支付
        if (order.getStatus() == Orders.TO_BE_CONFIRMED) {
            //如果已支付，需要进行退款
            String refund = weChatPayUtil.refund(
                    order.getNumber(),
                    order.getNumber(),
                    order.getAmount(),
                    order.getAmount()
            );
            //修改订单支付状态为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        //修改订单状态，订单取消原因，订单取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id 订单id
     */
    @Override
    public void repetition(Long id) {
        //再来一单就是将原订单中的商品重新加入到购物车中
        //1.先通过订单id查询订单对应的菜品信息
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        //2.再将这些菜品信息，添加到购物车中
        if (orderDetails != null && orderDetails.size() > 0) {
            for (OrderDetail orderDetail : orderDetails) {
                ShoppingCart shoppingCart = new ShoppingCart();
                //拷贝相同的数据
                BeanUtils.copyProperties(orderDetail, shoppingCart);
                //设置用户id
                shoppingCart.setUserId(BaseContext.getCurrentId());
                //设置创建时间
                shoppingCart.setCreateTime(LocalDateTime.now());
                //添加到购物车
                shoppingCartMapper.insert(shoppingCart);
            }
        }
    }

    /**
     * 催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id);

        map.put("content", "订单号：" + order.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
